package Example;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author:  LiuTao
 * Version: 1.0
 * Date:    2023-12-06  20:52
 */
class MyBlockingQueue {
    private String[] elems = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    private Object locker = new Object();

    public MyBlockingQueue(int capacity) {
        elems = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized (locker) {
            while(size >= elems.length) {
                locker.wait();
            }
            elems[tail] = elem;
            tail++;
            size++;
            if(size >= elems.length) {
                tail = 0;
            }
            locker.notify();
        }
    }

    public String take() throws InterruptedException {
        String elem = null;
        synchronized (locker) {
            while(size == 0) {
                locker.wait();
            }
            elem = elems[head];
            head++;
            size--;
            if(head >= elems.length) {
                head = 0;
            }
        }
        return elem;
    }

}
public class Main1 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(1000000);
        Thread thread = new Thread(() -> {
            int i = 1;
            while(true) {
                try {
                    myBlockingQueue.put(i + "");
                    System.out.println("生产元素 " + i);
                    i++;
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread thread1 = new Thread(() -> {
            String elem = null;
            while(true) {
                try {
                    elem = myBlockingQueue.take();
                    System.out.println("消费元素 " + elem);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });
        thread1.start();
        thread.start();
    }
}
